import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    currentMerchantId: null // 当前购物车商家ID，用于防止跨商家添加商品
  }),
  getters: {
    // 购物车商品总数
    totalCount: (state) => {
      return state.items.reduce((total, item) => total + item.quantity, 0)
    },
    // 购物车商品总价
    totalPrice: (state) => {
      return state.items.reduce((total, item) => total + item.price * item.quantity, 0)
    },
    minOrderDifference: (state) =>(minPrice) => {
      return Math.max((minPrice - state.totalPrice).toFixed(2), 0)
    },
    // 购物车是否为空
    isEmpty: (state) => state.items.length === 0
  },
  actions: {
    // 添加商品到购物车
    addToCart(product, specifications = [], quantity = 1) {
      // 如果购物车为空，设置当前商家ID
      if (this.isEmpty) {
        this.currentMerchantId = product.merchantId
      }
      
      // 检查是否跨商家添加商品
      if (product.merchantId !== this.currentMerchantId) {
        uni.showModal({
          title: '提示',
          content: '不能同时添加不同商家的商品，是否清空当前购物车？',
          success: (res) => {
            if (res.confirm) {
              this.clearCart()
              this.currentMerchantId = product.merchantId
              this._addItem(product, specifications, quantity)
            }
          }
        })
        return
      }
      
      this._addItem(product, specifications, quantity)
    },
    
    // 内部方法：添加商品到购物车
    _addItem(product, specifications = [], quantity = 1) {
      // 生成规格字符串，用于判断是否为相同商品
      const specsStr = specifications.map(spec => `${spec.name}:${spec.value}`).join(',')
      //计算所选规格的加价
      const addedPrice = specifications.reduce((total, spec) => total + spec.price, 0)
      // 查找购物车中是否已存在相同商品
      const existingItemIndex = this.items.findIndex(item => 
        item.id === product.id && item.specificationsStr === specsStr
      )
      
      if (existingItemIndex > -1) {
        // 如果已存在，增加数量
        this.items[existingItemIndex].quantity += quantity
      } else {
        // 如果不存在，添加新商品
        this.items.push({
          id: product.id,
          name: product.name,
          price: product.price + addedPrice,
          originalPrice: product.originalPrice + addedPrice,
          image: product.image,
          merchantId: product.merchantId,
          specifications: specifications,
          specificationsStr: specsStr,
          quantity: quantity,
          packagingFee: product.packagingFee
        })
      }
      
      // 保存到本地存储
      this._saveToStorage()
      
      // 显示添加成功提示
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      })
    },
    
    // 更新购物车商品数量
    updateItemQuantity(index, quantity) {
      if (index >= 0 && index < this.items.length) {
        if (quantity <= 0) {
          // 如果数量小于等于0，从购物车中移除
          this.removeItem(index)
        } else {
          // 更新数量
          this.items[index].quantity = quantity
          this._saveToStorage()
        }
      }
    },
    
    // 从购物车中移除商品
    removeItem(index) {
      if (index >= 0 && index < this.items.length) {
        this.items.splice(index, 1)
        
        // 如果购物车为空，重置商家ID
        if (this.isEmpty) {
          this.currentMerchantId = null
        }
        
        this._saveToStorage()
      }
    },
    
    // 清空购物车
    clearCart() {
      this.items = []
      this.currentMerchantId = null
      this._saveToStorage()
    },
    
    // 保存购物车数据到本地存储
    _saveToStorage() {
      uni.setStorageSync('cart', {
        items: this.items,
        merchantId: this.currentMerchantId
      })
    },
    
    // 从本地存储加载购物车数据
    loadFromStorage() {
      const cartData = uni.getStorageSync('cart')
      if (cartData) {
        this.items = cartData.items || []
        this.currentMerchantId = cartData.merchantId
      }
    }
  }
})